package com.fdb.efp.nls.service.impl;

import com.fdb.basic.framework.core.base.FrameworkService;
import com.fdb.basic.framework.core.util.DateUtility;
import com.fdb.efp.nls.service.dao.*;
import com.fdb.efp.nls.service.domain.*;
import com.fdb.efp.nls.service.facade.AccoutErroTempService;
import com.fdb.efp.nls.service.facade.LoanPolicyService;
import com.fdb.efp.nls.service.vo.LoanPolicyVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * ServiceImpl: 马上保单信息
 * <p>
 * 
 * @author cyj
 * @date 2018-12-27
 */
@Service("loanPolicyService")
public class LoanPolicyServiceImpl implements LoanPolicyService, FrameworkService {

	private static Logger logger = LoggerFactory.getLogger(LoanPolicyServiceImpl.class);

	@Autowired
	private LoanPolicyDao loanPolicyDao;

	@Autowired
	private GzBankPolicyFileTempDao gzBankPolicyFileTempDao;
	@Autowired
	private PolicyDetailAcountTempDao policyDetailAcountTempDao;
	@Autowired
	private AccoutErroTempDao accoutErroTempDao;
	@Autowired
	private AccoutErroTempService accoutErroTempService;
	@Autowired
	private AccLoanDao accLoanDao;

	/**
	 * 
	 * 同步马上的数据 新增 保单 <br>
	 * 0.2:ludayong:2019年3月6日 下午5:10:56:修复保单临时信息为空时，出现空指针异常<br>
	 * @author cenyj
	 * @since 2018年12月28日 下午3:33:37
	 * @date 2019年3月6日 下午5:10:56
	 * @version 0.2
	 */
	public boolean batchLoanPolicyFromMaTxt() throws Exception {
		boolean rs = false;
		try {
			// 分页大小
			Integer pageSize = 1000;
			// 分页信息
			GzBankPolicyFileTemp pageInfo = new GzBankPolicyFileTemp();
			// 页数
			int page = 1;
			// pageSize初始化
			if (pageSize > 0) {
				pageInfo.setSize(pageSize);
			} else {
				pageInfo.setSize(1000);
			}
			// 判断循环次数
			int size = gzBankPolicyFileTempDao.queryCount();
			String size_msg = "【保单信息表临时表】数据量：" + size;
			logger.info(size_msg, "message{}");
			int loopCount = (size / pageInfo.getSize()) + 1;
			// 贷款金额
			Double businessSum = 0.0;
			for (int i = 0; i < loopCount; i++) {
				String page_msg = "【保单信息表临时表】当前页数：" + pageInfo.getPage() + "，分页大小：" + pageInfo.getSize();
				logger.info(page_msg, "message{}");
				// 分页查询【保单信息表临时表】数据
				List<GzBankPolicyFileTemp> tempList = gzBankPolicyFileTempDao.queryByPage(pageInfo);
				if (Objects.nonNull(tempList) && !tempList.isEmpty()) {
					//分页同步保单信息
					syncLoanPolicyInfo(tempList);
					// 贷款金额
					businessSum += tempList.stream().mapToDouble(GzBankPolicyFileTemp::getBusinessSum).sum();
				}
				pageInfo.setPage(++page);
			}

			// 先 对账表，看是否能对应上
			logger.info("日终批量修改从马上同步过来的临时表数据到还款明细表：");
			int num = 0;
			// 先校对 对账临时表的记录条数跟同步过来的数据是否一致 如果一致 再批量 把临时表的数据同步到本地
			// 临时表
			//List<GzBankPolicyFileTemp> list = gzBankPolicyFileTempDao.getGzBankPolicyFileTempList();
			//同步信息为空，返回false
			//if(Objects.isNull(list)) {
				//logger.info("日终批量-同步马上的保单信息明细信息为空！");
				//return rs;
			//}
			// 对账列表
			List<PolicyDetailAcountTemp> accountList = policyDetailAcountTempDao.getPolicyDetailAcountTempList();
			// 对账临时表
			PolicyDetailAcountTemp accountTempModel = null;//new PolicyDetailAcountTemp();
			// 贷款金额
			//Double businessSum = list.stream().mapToDouble(GzBankPolicyFileTemp::getBusinessSum).sum();
			BigDecimal businessSumTotal = BigDecimal.valueOf(businessSum == null ? 0 : businessSum);
			int accountCountTemp = 0;// 对账表记录的条数
			int loanTempDatasize = 0;// 实际同步过来的数据总条数
			if (accountList != null && accountList.size() > 0) {
				accountTempModel = accountList.get(0);
			}
			if (accountTempModel != null) {
				accountCountTemp = accountTempModel.getDataAcount() == null ? 0 : accountTempModel.getDataAcount();
				if (accountTempModel.getLoanMoneyTotal().compareTo(businessSumTotal) != 0) {
					try {
						// 如果 贷款金额总额 不一样，则记录到erro_msg表
						AccoutErroTemp erroMsgModel = new AccoutErroTemp();
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String currDate = sdf.format(new Date());
						String erroMsg = "马上传过来的对账临时表的贷款金额总金额和保单列表的总金额对应不上";
						String tableName = "GzBankPolicyFileTemp";
						String remark ="马上传过来的保单临时列表的总金额" + businessSumTotal  +"对账临时表的贷款金额总金额" + accountTempModel.getLoanMoneyTotal() + "!" 
								+ "!";
						erroMsgModel.setCreateData(currDate);
						erroMsgModel.setErroMsg(erroMsg);
						erroMsgModel.setRemark(remark);
						erroMsgModel.setTableName(tableName);
						num = accoutErroTempDao.insert(erroMsgModel);
						if (num != 1) {
							logger.error("新增对账异常信息出错!");
						}

					} catch (Exception e) {
						logger.error("新增对账异常信息出错!", e);
						e.printStackTrace();
					}
				}
			}
			//loanTempDatasize = list.size();
			loanTempDatasize = size;
			logger.info("对账表记录的条数TempDatasize：" + loanTempDatasize + "实际同步过来的数据总条数TempDatasize" + loanTempDatasize);
			if (loanTempDatasize != accountCountTemp) {
				try {
					// 如果条数不一样，则记录到erro_msg表
					AccoutErroTemp erroMsgModel = new AccoutErroTemp();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String currDate = sdf.format(new Date());
					String erroMsg = "记录条数不对";
					String tableName = "GzBankPolicyFileTemp";
					String remark = "同步过来的临时表马上保单GzBankPolicyFileTemp列表记录总条数" + loanTempDatasize + "条" + "对账表记录条数" + accountCountTemp + "条";
					erroMsgModel.setCreateData(currDate);
					erroMsgModel.setErroMsg(erroMsg);
					erroMsgModel.setRemark(remark);
					erroMsgModel.setTableName(tableName);
					num = accoutErroTempDao.insert(erroMsgModel);
					if (num != 1) {
						logger.error("记录条数不对，新增对账异常信息出错!");
					}
				} catch (Exception e) {
					logger.error("记录条数不对，新增对账异常信息出错!", e);
					e.printStackTrace();
				}
			}
			rs = true;
		} catch (Exception e) {
			logger.error("保单数据发生异常!", e);
			e.printStackTrace();
			String tableName = "LoanPolicy保单表";
			String erroMsg = "";
			String tempTotal = "";
			String acountTotal = "";
			String type = "0";
			String updateDelInster = "";
			String no ="";
			String eMsg = e.getMessage();
			accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no,
					eMsg);
		}
		return rs;
	}

	/**
	 * 新增操作
	 */
	public int insertLoanPolicy(LoanPolicyVO inLoanPolicy) {
		logger.debug("当前新增数据为:" + inLoanPolicy.toString());
		int num = 0;
		try {
			LoanPolicy loanPolicy = new LoanPolicy();
			beanCopy(inLoanPolicy, loanPolicy);
			num = loanPolicyDao.insertLoanPolicy(loanPolicy);
		} catch (Exception e) {
			logger.error("新增数据发生异常!", e);
			num = -1;
		}
		logger.debug("当前新增数据条数为:" + num);
		return num;
	}

	/**
	 * 删除操作
	 */
	public int deleteByPk(LoanPolicyVO inLoanPolicyVo) {
		logger.debug("当前删除数据条件为:" + inLoanPolicyVo);
		int num = 0;
		try {
			LoanPolicy loanPolicy = new LoanPolicy();
			beanCopy(inLoanPolicyVo, loanPolicy);
			num = loanPolicyDao.deleteByPk(loanPolicy);
		} catch (Exception e) {
			logger.error("删除数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:" + inLoanPolicyVo + "删除的数据条数为" + num);
		return num;
	}

	/**
	 * 更新操作
	 */
	public int updateByPk(LoanPolicyVO inLoanPolicyVo) {
		logger.debug("当前修改数据为:" + inLoanPolicyVo.toString());
		int num = 0;
		try {
			LoanPolicy loanPolicy = new LoanPolicy();
			beanCopy(inLoanPolicyVo, loanPolicy);
			num = loanPolicyDao.updateByPk(loanPolicy);
		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:" + inLoanPolicyVo + "修改的数据条数为" + num);
		return num;
	}

	/**
	 * 查询操作
	 */
	public LoanPolicyVO queryByPk(LoanPolicyVO inLoanPolicyVo) {

		logger.debug("当前查询参数信息为:" + inLoanPolicyVo);
		try {
			LoanPolicy queryLoanPolicy = new LoanPolicy();
			beanCopy(inLoanPolicyVo, queryLoanPolicy);
			LoanPolicy queryRslLoanPolicy = loanPolicyDao.queryByPk(queryLoanPolicy);
			if (Objects.nonNull(queryRslLoanPolicy)) {
				LoanPolicyVO outLoanPolicyVo = beanCopy(queryRslLoanPolicy, new LoanPolicyVO());
				logger.debug("当前查询结果为:" + outLoanPolicyVo.toString());
				return outLoanPolicyVo;
			} else {
				logger.debug("当前查询结果为空!");
			}
		} catch (Exception e) {
			logger.error("查询数据发生异常!", e);
		}
		return null;
	}

	/**
	 * 查询用户权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<LoanPolicyVO> queryAllOwner(LoanPolicyVO loanPolicyVo) {

		logger.debug("当前查询本人所属数据信息的参数信息为:");
		List<LoanPolicyVO> list = null;
		try {
			List<LoanPolicy> loanPolicys = loanPolicyDao.queryAllOwnerByPage(loanPolicyVo);
			logger.debug("当前查询本人所属数据信息的结果集数量为:" + loanPolicys.size());
			// pageSet(loanPolicys, loanPolicyVo);
			list = (List<LoanPolicyVO>) beansCopy(loanPolicys, LoanPolicyVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}

		return list;

	}

	/**
	 * 查询当前机构权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<LoanPolicyVO> queryAllCurrOrg(LoanPolicyVO loanPolicyVo) {

		logger.debug("当前查询本人所属机构数据信息的参数信息为:");
		List<LoanPolicy> loanPolicys = loanPolicyDao.queryAllCurrOrgByPage(loanPolicyVo);
		logger.debug("当前查询本人所属机构数据信息的结果集数量为:" + loanPolicys.size());
		List<LoanPolicyVO> list = null;
		try {
			// pageSet(loanPolicys, loanPolicyVo);
			list = (List<LoanPolicyVO>) beansCopy(loanPolicys, LoanPolicyVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}

		return list;

	}

	/**
	 * 查询当前机构及下属机构权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<LoanPolicyVO> queryAllCurrDownOrg(LoanPolicyVO loanPolicyVo) {

		logger.debug("当前查询本人所属机构及以下数据信息的参数信息为:");
		List<LoanPolicy> loanPolicys = loanPolicyDao.queryAllCurrDownOrgByPage(loanPolicyVo);
		logger.debug("当前查询本人所属机构及以下数据信息的结果集数量为:" + loanPolicys.size());
		List<LoanPolicyVO> list = null;
		try {
			// pageSet(loanPolicys, loanPolicyVo);
			list = (List<LoanPolicyVO>) beansCopy(loanPolicys, LoanPolicyVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}

		return list;

	}
	
	
	/**
	 * 查询马上的数据 新增
	 * 保单明细表	
	 * @description:TODO
	 * @date:2019年4月20日 下午3:33:37
	 * @author:weijj
	 */
//	public LoanPolicyVO queryByInsureNo(LoanPolicyVO loanPolicyVo1) {
//
//		logger.debug("当前查询参数信息为:" + loanPolicyVo1);
//		try {
//			LoanPolicy queryLoanPolicy = new LoanPolicy();
//			beanCopy(loanPolicyVo1, queryLoanPolicy);
//			LoanPolicy queryRslLoanPolicy = loanPolicyDao.queryByInsureNo(queryLoanPolicy);
//			if (Objects.nonNull(queryRslLoanPolicy)) {
//				LoanPolicyVO outLoanPolicyVo = beanCopy(queryRslLoanPolicy, new LoanPolicyVO());
//				logger.debug("当前查询结果为:" + outLoanPolicyVo.toString());
//				return outLoanPolicyVo;
//			} else {
//				logger.debug("当前查询结果为空!");
//			}
//		} catch (Exception e) {
//			logger.error("查询数据发生异常!", e);
//		}
//		return null;
//	}


	/**
	 *需求编号：【2019D1204】（马上账务文件同步分页处理）
	 *问题编号：【2019D1204】（马上账务文件同步分页处理）
	 *开发人员：【ludayong】
	 *创建日期：【2019/11/27 11:31】
	 *功能描述：分页同步保单信息
	 *修改日期：【2019/11/27 11:31】
	 *修改描述：
	 * 修改人：【wengqingw】
	 * 修改内容：【2020D0553】新增/更新保单明细表时，同步更新acc_loan表assure_means3(保险公司)字段
	 */
	public void syncLoanPolicyInfo(List<GzBankPolicyFileTemp> list) {
		try {
			//更新或者新增的记录数
			int num = 0;
			int num1 = 0;
			// 本地表进行 新增
			if (list != null && list.size() > 0) {
				for (GzBankPolicyFileTemp fileTemp : list) {
					// 因爲有可能出现我们审批没有通过，但马上放款的数据，所以先判断本地借据表是否有对应的借据号 有再新增
					AccLoan acc_loan = new AccLoan();
					acc_loan.setBillNo(fileTemp.getLoanNo());
					AccLoan accLoan = accLoanDao.queryByPk(acc_loan);
					if (accLoan != null) {
						try {
							LoanPolicyVO loanPolicy = new LoanPolicyVO();
							/** 保单号 */
							loanPolicy.setPolicynbr(fileTemp.getPolicyNbr());
							/** 贷款账号（借据号） */
							loanPolicy.setLoanNo(fileTemp.getLoanNo());
							/** 贷款金额 */
							loanPolicy
									.setBusinessSum(BigDecimal.valueOf(fileTemp.getBusinessSum() == null ? 0 : fileTemp.getBusinessSum()));
							/** 发放日期 */
							SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd");//

							logger.info("格式化前的发放日期："+fileTemp.getPutOutDate());

							//loanPolicy.setPutOutDate(sdfTime.format(fileTemp.getPutOutDate()));
							String putOutDate = fileTemp.getPutOutDate() == null ? "" : fileTemp.getPutOutDate();
							if (putOutDate.indexOf("/") >= 0) {
								putOutDate = putOutDate.replace("/", "-");
							} else if (putOutDate.length() == 8) {
								putOutDate = DateUtility.format8To10(fileTemp.getPutOutDate());
							}
							loanPolicy.setPutOutDate(putOutDate);
							//loanPolicy.setPutOutDate(DateUtility.format8To10(fileTemp.getPutOutDate()));
							logger.info("格式化后的发放日期："+DateUtility.format8To10(fileTemp.getPutOutDate()));
							loanPolicy.setInsuInd(fileTemp.getInsuInd());
							//loanPolicy.setInsureNo(fileTemp.getInsureNo());
							//num = insertLoanPolicy(loanPolicy);

							//查询保单明细信息是否存在，存在则更新，不存在则新增
							LoanPolicyVO queryLoanPolicyVO = queryByPk(loanPolicy);
							if(Objects.nonNull(queryLoanPolicyVO)) {
								//更新保单明细信息
								num = updateByPk(loanPolicy);
								//更新保单明细信息时同步更新acc_loan表的assure_means3(保险公司)字段
								accLoan.setAssureMeans3(fileTemp.getInsuInd());
								num1 = accLoanDao.updateByPk(accLoan);
							}else {
								//新增保单明细信息
								num = insertLoanPolicy(loanPolicy);
								//新增保单明细信息时同步更新acc_loan表的assure_means3(保险公司)字段
								accLoan.setAssureMeans3(fileTemp.getInsuInd());
								num1 = accLoanDao.updateByPk(accLoan);
							}
							if (num != 1) {
								logger.error("新增数据发生异常!");
								String tableName = "LoanPolicy保单表";
								String erroMsg = "";
								String tempTotal = "";
								String acountTotal = "";
								String type = "0";
								String updateDelInster = "新增";
								String no = fileTemp.getLoanNo();
								String eMsg = "新增数据发生异常!";
								accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no,
										eMsg);
							}
							if (num1 != 1) {
								logger.error("更新数据发生异常!");
								String tableName = "AccLoan借据表";
								String erroMsg = "";
								String tempTotal = "";
								String acountTotal = "";
								String type = "0";
								String updateDelInster = "新增";
								String no = fileTemp.getLoanNo();
								String eMsg = "更新数据发生异常!";
								accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no,
										eMsg);
							}
						} catch (Exception e) {
							logger.error("新增数据发生异常!", e);
							e.printStackTrace();
							String tableName = "LoanPolicy保单表";
							String erroMsg = "";
							String tempTotal = "";
							String acountTotal = "";
							String type = "0";
							String updateDelInster = "新增";
							String no = fileTemp.getLoanNo();
							String eMsg = e.getMessage();
							accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no,
									eMsg);
						}
					} else {
						logger.info("没有对应的借据数据信息!");
						String tableName = "LoanPolicy保单表";
						String erroMsg = "";
						String tempTotal = "";
						String acountTotal = "";
						String type = "0";
						String updateDelInster = "新增";
						String no = fileTemp.getLoanNo();
						String eMsg = "没有对应的借据数据信息!";
						accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no, eMsg);
					}
				}
			}
		} catch (Exception e) {
			logger.error("同步马上保单信息数据发生异常!", e);
		}
	}
}
